<template>
	<view>
		<view class="title text-32px flex flex-x-between">
			<text>按时间段查询</text>
		</view>
		<DataCard>
			<template #content>
				<view>
					<view class="p-20px flex">
						<view class="w-1-2 flex flex-y-center" @click="openDateTime('start')">
							<image src="../../static/business-icon/icon-shijian.svg" mode=""
								class="w-60px h-60px mr-10px"></image>
							<view class="flex flex-y">
								<text>开始时间</text>
								<text class="text-28px">{{state.startDateStr}}</text>
							</view>
						</view>
						<view class="w-1-2 flex flex-y-center" @click="openDateTime('end')">
							<image src="../../static/business-icon/icon-shijian.svg" mode=""
								class="w-60px h-60px mr-10px"></image>
							<view class="flex flex-y">
								<text>结束时间</text>
								<text class="text-28px">{{state.endDateStr}}</text>
							</view>
						</view>
						<uv-datetime-picker ref="datetimePicker" v-model="state.date" mode="datetime"
							@confirm="setDateTime">
						</uv-datetime-picker>
					</view>
					<uv-line></uv-line>
					<view class="w-1-2 py-20px m-a">
						<uv-button type="primary" shape="circle" text="查询" @click="search"></uv-button>
					</view>
				</view>
			</template>
		</DataCard>
	</view>
</template>

<script setup name='DateSearch'>
	import {
		ref,
		reactive
	} from 'vue';
	import DataCard from '@/components/DataCard.vue'

	const datetimePicker = ref()
	const state = reactive({
		date: Number(new Date()),
		dateType: 'start',
		startDate: null,
		startDateStr: null,
		endDate: null,
		endDateStr: null
	})

	const openDateTime = (type) => {
		datetimePicker.value.open()
		state.dateType = type
		if (state.startDate || state.endDate) {
			state.date = Number(state[type + 'Date'])
		}
	}

	const setDateTime = (e) => {
		state[state.dateType + 'Date'] = e.value
		state[state.dateType + 'DateStr'] = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh-MM')
		if (state.dateType === 'start') {
			if (!state.endDate) {
				state.endDate = e.value
				state.endDateStr = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh-MM')
			}
			if (state.startDate > state.endDate) {
				state.endDate = e.value
				state.endDateStr = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh-MM')
			}
		} else if (state.dateType === 'end') {
			if (!state.startDate) {
				state.startDate = e.value
				state.startDateStr = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh-MM')
			}
			if (state.startDate > state.endDate) {
				state.startDate = e.value
				state.startDateStr = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh-MM')
			}
		}
	}

	const search = () => {
		if (!state.startDate || !state.endDate) {
			uni.showToast({
				title: '请先选择时间',
				icon: 'error',
			});
			return
		}
	}
</script>